#coding:utf-8

import requests
import time
import json
from mysql import sqlExecute

"""
爬取全国疫情总体情况
"""

def get_url():
    # 抓取数据
    ## 先把数据都爬下来，查看数据结构，明确要整理保存的数据
    list = []
    # url_1包含中国各省市当日实时数据
    url_1 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
    list.append(url_1)
    # url_2包含中国历史数据及每日新增数据
    url_2 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_other'
    list.append(url_2)
    # url_3包含全球实时数据及历史数据、中国输入病例
    url_3 = 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_foreign'
    list.append(url_3)
    return list


def main():
    datalist = getData()
    print(datalist)
    # result = saveData(datalist)
    # if result is None:
    #     print("数据存储失败")
    # else:
    #     print("数据存储成功")


#第一步：爬取网页数据
def getData():
    datalist = {}
    #国内各省市当日实时数据
    # time1 = int(time.time()*1000)
    url1 = get_url()[0]
    # url_2包含中国历史数据及每日新增数据
    url2 = get_url()[1]
    # url_3包含全球实时数据及历史数据、中国输入病例
    url3 = get_url()[2]
    header = {"User-Agent": "Mozilla/5.0 (Linux; Android 6.0.1; Moto G (4)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36"}
    result = requests.get(url=url1,headers = header)
    data = result.json()['data']
    print(result)
    # lastUpdateTime chinaTotal chinaAdd isShowAdd showAddSwitch areaTree
    if result.status_code == 200:
        data = json.loads(result.json()['data'])
        # lastUpdateTime ：最后更新时间
        datalist['lastUpdateTime'] = data['lastUpdateTime']
        # chinaTotal ：累计值
        chinaTotal = data['chinaTotal']
        datalist['total_confirm'] = chinaTotal['confirm']  # confirm确诊
        datalist['total_heal'] = chinaTotal['heal'] # heal治愈
        datalist['total_dead'] = chinaTotal['dead'] # dead死亡
        datalist['total_nowConfirm'] = chinaTotal['nowConfirm'] # nowConfirm现有确诊
        datalist['total_suspect'] = chinaTotal['suspect'] # suspect疑似
        datalist['total_nowSevere'] = chinaTotal['nowSevere'] # nowSevere重症
        return datalist
    else:
        return datalist


# 第二步： 将数据保存到数据库中
def saveData(datalist):
    sqlDb = sqlExecute.MysqlDb()
    sql = "insert into covid_total(lastUpdateTime,total_confirm,total_heal,total_dead,total_nowConfirm,total_suspect,total_nowSevere) " \
          "values('{}',{},{},{},{},{},{})".format(str(datalist['lastUpdateTime']),datalist['total_confirm'],datalist['total_heal'],datalist['total_dead'],datalist['total_nowConfirm'],datalist['total_suspect'],datalist['total_nowSevere'])
    result = sqlDb.execute_sql(sql)
    return result


if __name__ == "__main__":
    main()